package com.doraro.platform.common.utils;

import com.doraro.platform.common.exception.ApiGlobalException;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.http.HttpStatus;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * {
 * meta:{"code":code,“msg”:message}
 * data:{....}
 * }
 */
@Data
@Accessors(chain = true)
public class Result {

    /**
     * 消息头meta 存放状态信息 code message
     */
    private Map<String, Object> meta = new HashMap<String, Object>();
    /**
     * 消息内容  存储实体交互数据
     */
    private Map<String, Object> data = new HashMap<String, Object>();


    public Result addMeta(String key, Object object) {
        this.meta.put(key, object);
        return this;
    }

    public Result addData(String key, Object object) {
        this.data.put(key, object);
        return this;
    }

    public Result ok() {
        this.addMeta("isSuccess", Boolean.TRUE);
        this.addMeta("code", HttpStatus.OK);
        this.addMeta("msg", "success");
        this.addMeta("timestamp", LocalDateTime.now());
        return this;
    }

    public Result ok(HttpStatus statusCode, String statusMsg) {
        this.addMeta("isSuccess", Boolean.TRUE);
        this.addMeta("code", statusCode);
        this.addMeta("msg", statusMsg);
        this.addMeta("timestamp", LocalDateTime.now());
        return this;
    }

    public Result error() {
        this.addMeta("isSuccess", Boolean.FALSE);
        this.addMeta("code", HttpStatus.INTERNAL_SERVER_ERROR);
        this.addMeta("msg", "未知异常，请联系管理员");
        this.addMeta("timestamp", LocalDateTime.now());
        return this;
    }

    public Result error(HttpStatus statusCode, String statusMsg) {
        this.addMeta("isSuccess", Boolean.FALSE);
        this.addMeta("code", statusCode);
        this.addMeta("msg", statusMsg);
        this.addMeta("timestamp", LocalDateTime.now());
        return this;
    }

    public Result error(ApiGlobalException ex) {
        this.addMeta("isSuccess", Boolean.FALSE);
        this.addMeta("code", ex.getCode());
        this.addMeta("msg", ex.getMsg());
        this.addMeta("timestamp", LocalDateTime.now());
        return this;
    }
}
